package com.func.boom.filter;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Yulei
 * @date 2020-08-23 22:50:30
 * @desc
 */
@Slf4j
@RefreshScope
public class TokenFilter implements GlobalFilter, Ordered {

    @Value("${request.white.list: ''}")
    private String requestWhite;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 请求路径
        String path = exchange.getRequest().getPath().toString();
        String token = exchange.getRequest().getHeaders().getFirst("token");

        String[] whiteList = requestWhite.split(",");
        if (!ArrayUtil.contains(whiteList, path)) {
            if (StrUtil.isBlank(token)) {
                log.info("网关服务验证token为空！！！");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            } else {
                //验证token是否解析成功

            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
